package org.example.lotterysystem.controller;


import lombok.extern.slf4j.Slf4j;
import org.example.lotterysystem.common.pojo.CommonResult;
import org.example.lotterysystem.common.utils.JacksonUtil;
import org.example.lotterysystem.controller.param.DrawPrizeParam;
import org.example.lotterysystem.controller.param.ShowWinningRecordsParam;
import org.example.lotterysystem.controller.result.WinningRecordsResult;
import org.example.lotterysystem.service.DrawPrizeService;
import org.example.lotterysystem.service.dto.WinningRecordDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class DrawPrizeController {

    @Autowired
    private DrawPrizeService drawPrizeService;

    @RequestMapping("/draw-prize")
    public CommonResult<Boolean> drawPrize(@RequestBody @Validated DrawPrizeParam param) {
        log.info("drawPrize DrawPrizeParam:{}", JacksonUtil.writeValueAsString(param));
        drawPrizeService.drawPrize(param);
        return CommonResult.success(true);
    }

    @RequestMapping("/winning-records/show")
    public CommonResult<List<WinningRecordsResult>> showWinningRecords(
            @RequestBody @Validated ShowWinningRecordsParam param) {
        log.info("showWinningRecords ShowWinningRecordsParam:{}", JacksonUtil.writeValueAsString(param));
        List<WinningRecordDTO> winningRecordDTOList = drawPrizeService.getRecords(param);
        return CommonResult.success(convertToWinningRecordResultList(winningRecordDTOList));
    }

    private List<WinningRecordsResult> convertToWinningRecordResultList(List<WinningRecordDTO> winningRecordDTOList) {
        if (CollectionUtils.isEmpty(winningRecordDTOList)) {
            return List.of();
        }
        log.info("winningRecordDTOList: {}", JacksonUtil.writeValueAsString(winningRecordDTOList));
        return winningRecordDTOList.stream().map(winningRecordDTO -> {
            WinningRecordsResult winningRecordsResult = new WinningRecordsResult();
            winningRecordsResult.setWinnerId(winningRecordDTO.getWinnerId());
            winningRecordsResult.setWinnerName(winningRecordDTO.getWinnerName());
            winningRecordsResult.setPrizeName(winningRecordDTO.getPrizeName());
            winningRecordsResult.setPrizeTier(winningRecordDTO.getPrizeTier().getMessage());
            winningRecordsResult.setWinningTime(winningRecordDTO.getWinningTime());
            return winningRecordsResult;
        }).toList();
    }

}
